package com.sskj.b70.v.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.adapter.slimadapter.IViewInjector;
import com.sskj.b70.adapter.slimadapter.SlimAdapter;
import com.sskj.b70.adapter.slimadapter.SlimInjector;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.m.HttpConfig;
import com.sskj.b70.m.bean.FabiOrderBean;
import com.sskj.b70.p.activity.FabiSellDetailPresenter;
import com.sskj.b70.utils.BottomUpUtil;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.ImageUtil;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.utils.RxSchedulersHelper;
import com.sskj.b70.utils.TimeFormatUtil;
import com.sskj.b70.utils.TipUtil;
import com.sskj.b70.v.base.BaseActivity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * C2C交易订单界面
 */
public class FabiSellDetailActivity extends BaseActivity<FabiSellDetailPresenter> {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_id_code)  // 订单号
            TextView tvIdCode;
    @BindView(R.id.tv_sale_to)  // 您向李××出售2.0000USDT
            TextView tvSaleTo;
    @BindView(R.id.tv_single_price)  // 单价
            TextView tvSinglePrice;
    @BindView(R.id.tv_all_price)   // 总价
            TextView tvAllPrice;
    @BindView(R.id.tv_desc)  // 等待对方付款，李××将于08分52秒内完成支付，付款参考号是：
            TextView tvDesc;
    @BindView(R.id.tv_control)  // 取消订单
            TextView tvControl;
    @BindView(R.id.tv_control_second)
    TextView tvControlSecond;
    @BindView(R.id.tv_notify)  // 付款成功后，请点击按钮告知对方
            TextView tvNotify;
    @BindView(R.id.tv_order_remark)  // RecycleView下的备注
            TextView tvOrderRemark;
    @BindView(R.id.bt_control)  // 等待对方支付
            Button btControl;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private boolean isBuy;   // false 出售--2   true求购--1
    private HashMap<String, Integer> payMap;
    private String orderNum;
    private AlertDialog payTipDialog;
    private EditText etReason;
    private Spinner spinner;
    private FabiOrderBean.PayListBean orderData;
    private BottomSheetDialog codeDialog;
    private SlimAdapter<FabiOrderBean.PayListBean.PayType> slimAdapter;
    private DisposableSubscriber<Long> timeDispo;
    private int curPos;
    private HashMap<String, String> payTipMap;
    private AlertDialog tipCancleDialog;
    private AlertDialog tipAppealDialog;
    private AlertDialog qrDialog;
    private ImageView ivQR;
    private TextView tvQR;
    private DisposableSubscriber<Long> timerDispos;

    public static void start(Context context, String orderNum, boolean isBuy) {
        Intent starter = new Intent(context, FabiSellDetailActivity.class);
        starter.putExtra(Constants.ORDER_NUM, orderNum);
        starter.putExtra(Constants.IS_BUY, isBuy);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_fabi_sell_detail;
    }

    @Override
    public FabiSellDetailPresenter getPresenter() {
        return new FabiSellDetailPresenter();
    }

    @Override
    protected void initData() {
        payMap = new HashMap<>();
        payTipMap = new HashMap<>();
        payTipMap.put("1", App.INSTANCE.getString(R.string.strFabiSellDetailActivity1));
        payTipMap.put("2", App.INSTANCE.getString(R.string.strFabiSellDetailActivity3));
        payMap.put("1", R.mipmap.wei_xin);
        payMap.put("2", R.mipmap.zhifu_bao);
        payMap.put("3", R.mipmap.yinhang_ka);
        orderNum = getIntent().getStringExtra(Constants.ORDER_NUM);
        isBuy = getIntent().getBooleanExtra(Constants.IS_BUY, true);
        mPresenter.getOrderInfo(orderNum, isBuy ? "1" : "2", true);
        timerDispos = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                mPresenter.getOrderInfo(orderNum, isBuy ? "1" : "2", false);
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        };
        Flowable.interval(10, 10, TimeUnit.SECONDS)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(timerDispos);
    }

    @Override
    protected void initView() {
        ClickUtil.click(ivBack, this::finish);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapter = SlimAdapter.create().register(R.layout.recy_item_pay_type, new SlimInjector<FabiOrderBean.PayListBean.PayType>() {
            @Override
            public void onInject(FabiOrderBean.PayListBean.PayType data, IViewInjector injector) {
                injector.image(R.id.iv_pay_type, payMap.get(data.getPayType()))  //  微信头像/支付宝头像
                        .text(R.id.tv_pay_type, data.getPayType().equals("1") ? App.INSTANCE.getString(R.string.strFabiSellDetailActivity12) : data.getPayType().equals("2") ? App.INSTANCE.getString(R.string.strFabiSellDetailActivity14) : App.INSTANCE.getString(R.string.strFabiSellDetailActivity15))  // 微信/支付宝
                        .text(R.id.tv_pay_num, data.getPayType().equals("1") ? data.getWxAccount() : data.getPayType().equals("2") ? data.getAlipayAccount() : data.getBankCardNo()) // 微信号/支付宝号
                        .text(R.id.tv_pay_name, isBuy ? orderData.getUsername() : MyAppLication.getName())   // 姓名
                        .visibility(R.id.iv_pay_qrcode, "3".equals(data.getPayType()) ? View.INVISIBLE : View.VISIBLE)  // 微信二维码
                        .visibility(R.id.ll_bank, "3".equals(data.getPayType()) ? View.VISIBLE : View.GONE)
                        .clicked(R.id.iv_pay_qrcode, (v) -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            showQR();
                        })
                        .with(R.id.ll_bank, (v) -> {
                            if ("3".equals(data.getPayType())) {
                                ((TextView) v.findViewById(R.id.tv_pay_big_bank)).setText(data.getBankCardType());
                                ((TextView) v.findViewById(R.id.tv_pay_small_bank)).setText(data.getBankCardOpenBank());
                            } else {
                                ((TextView) v.findViewById(R.id.tv_pay_big_bank)).setText("");
                                ((TextView) v.findViewById(R.id.tv_pay_small_bank)).setText("");

                            }
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());

    }

    /**
     * 显示二维码弹窗
     */
    private void showQR() {
        FabiOrderBean.PayListBean.PayType dataItem = slimAdapter.getDataItem(curPos);
        if (qrDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view = View.inflate(this, R.layout.dialog_erweima, null);
            ivQR = view.findViewById(R.id.iv_erweima);
            tvQR = view.findViewById(R.id.tv_content);
            builder.setView(view);
            builder.setCancelable(true);
            qrDialog = builder.create();
        }
        ImageUtil.setImage(HttpConfig.BASE_URL + (dataItem.getPayType().equals("1") ? dataItem.getWxImg() : dataItem.getAliImg()), ivQR);
        tvQR.setText(payTipMap.get(dataItem.getPayType()));
        qrDialog.show();
    }

    /**
     * 显示申诉弹窗
     */
    private void showAppeal() {
        if (tipAppealDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view = View.inflate(this, R.layout.dialog_fabi_sell_detail_appeal, null);
            ClickUtil.click(view.findViewById(R.id.tv_cancel), () -> tipAppealDialog.dismiss());
            ClickUtil.click(view.findViewById(R.id.tv_apply), () -> {
                tipAppealDialog.dismiss();
                String type = spinner.getSelectedItem().toString();
                String reason = etReason.getText().toString();
                mPresenter.allegeOrder(orderNum, orderData.getId(), orderData.getRefer(), isBuy ? "1" : "2", type, reason);

            });
            builder.setView(view);
            builder.setCancelable(true);
            etReason = view.findViewById(R.id.et_reason);
            spinner = view.findViewById(R.id.spinner);
            tipAppealDialog = builder.create();
        }

        tipAppealDialog.show();
    }

    /**
     * 显示撤单提示
     */
    private void showCancelTip() {
        if (tipCancleDialog == null) {
            tipCancleDialog = new AlertDialog.Builder(this)
                    .setTitle(App.INSTANCE.getString(R.string.strFabiSellDetailActivity26))
                    .setMessage(App.INSTANCE.getString(R.string.strFabiSellDetailActivity27))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strFabiSellDetailActivity28), (dialog, which) -> {
                        dialog.dismiss();
                        mPresenter.cancleOrder(orderNum, orderData.getId(), isBuy ? "1" : "2");
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strFabiSellDetailActivity31), (dialog, which) -> dialog.dismiss()).create();
        }
        tipCancleDialog.show();
    }

    public void updateUI(FabiOrderBean.PayListBean data) {
        orderData = data;
        tvIdCode.setText(data.getDealEntrustNo());  // 订单号
        tvOrderRemark.setText(String.format(App.INSTANCE.getString(R.string.strFabiSellDetailActivity32), !TextUtils.isEmpty(data.getRemarkInfo()) ? data.getRemarkInfo() : App.INSTANCE.getString(R.string.strFabiSellDetailActivity33)));
        tvSinglePrice.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity34) + NumberUtil.keepMax4(data.getPrice()) + "CNY/USDT");
        tvAllPrice.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity36) + NumberUtil.keepMax4(data.getTotalPrice()) + "CNY");
        slimAdapter.updateData(data.getStockUserPayWays());
        btControl.setVisibility(View.VISIBLE);
        btControl.setEnabled(true);
        btControl.setTextColor(getResources().getColor(R.color.bull_black));
        String leftTime;
        if ("3".equals(data.getStatus()) || "5".equals(data.getStatus())) {//完成或取消状态取消定时刷新
            if (timerDispos != null && !timerDispos.isDisposed()) {
                timerDispos.dispose();
            }
        }
        if (data.getCountDownTime() != 0 && ("1".equals(data.getStatus()) || "4".equals(data.getStatus())||"2".equals(data.getStatus()))) {
            if (timeDispo != null && !timeDispo.isDisposed()) {
                timeDispo.dispose();
                timeDispo = null;
            }
            timeDispo = new DisposableSubscriber<Long>() {
                @Override
                public void onNext(Long aLong) {
                    updateTime(aLong);
                }

                @Override
                public void onError(Throwable t) {
                    System.out.println(t);
                }

                @Override
                public void onComplete() {

                }
            };
            Flowable.intervalRange(1, data.getCountDownTime(), 0, 1, TimeUnit.SECONDS)
                    .map(i -> data.getCountDownTime() - i)
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(timeDispo);
            leftTime = TimeFormatUtil.SF_FORMAT_D.format(new Date(Long.valueOf(data.getCountDownTime()) * 1000));

        } else {
            leftTime = App.INSTANCE.getString(R.string.strFabiSellDetailActivity43);
        }
        if (isBuy) {
            tvSaleTo.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity44) + data.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity45) + NumberUtil.keepMax4(data.getTotalNum()) + "USDT");
            switch (data.getStatus()) {
                case "1"://未确认待付款
                    String desc = App.INSTANCE.getString(R.string.strFabiSellDetailActivity48) + leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity49) + data.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity50) + data.getRefer() + "）";
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(desc);
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.RED), desc.indexOf(leftTime), desc.indexOf(leftTime) + leftTime.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tvDesc.setText(spannableStringBuilder);
                    tvNotify.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity52));
                    tvControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity53));
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity55));
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(tvControl, () -> showCancelTip());
                    ClickUtil.click(btControl, this::showPayTip);
                    break;
                case "2"://已付款
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity57) + data.getRefer() + "）");
                    tvNotify.setText(leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity59));
                    tvControl.setText("");
                    tvControlSecond.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity61));
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity62));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, this::showAppeal);
                    ClickUtil.click(btControl, () -> {
                    });
                    btControl.setEnabled(false);
                    btControl.setTextColor(getResources().getColor(R.color.white));
                    break;
                case "3"://已确认完成
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity64) + data.getRefer() + "）");
                    tvNotify.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity66));
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity28));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(btControl, this::finish);
                    break;
                case "4"://申述中
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity71) + data.getCommand() + ",\n付款参考号：" + data.getRefer());
                    tvNotify.setText(leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity59));
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity28));
                    ClickUtil.click(btControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(tvControl, this::finish);
                    btControl.setVisibility(View.INVISIBLE);
                    break;
                case "5":

                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity78));
                    tvNotify.setText("");
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity82));
                    btControl.setVisibility(View.VISIBLE);
                    btControl.setEnabled(false);
                    btControl.setTextColor(getResources().getColor(R.color.white));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(btControl, () -> {
                    });
                    break;

            }
        } else {
            tvSaleTo.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity44) + data.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity84) + NumberUtil.keepMax4(data.getTotalNum()) + "USDT");
            switch (data.getStatus()) {
                case "1"://未确认待付款
                    String desc = App.INSTANCE.getString(R.string.strFabiSellDetailActivity87) + data.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity88) + leftTime + "内完成支付，\n付款参考号：" + data.getRefer();
                    tvDesc.setText(desc);
                    tvNotify.setText("");
                    tvControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity53));
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity93));
                    btControl.setEnabled(false);
                    btControl.setTextColor(getResources().getColor(R.color.white));
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(tvControl, () -> showCancelTip());
                    ClickUtil.click(btControl, () -> {
                    });
                    break;
                case "2"://已付款
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity95) + data.getRefer());
                    tvNotify.setText("");
                    tvControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity61));
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity99));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControl, this::showAppeal);
                    ClickUtil.click(btControl, this::showCode);
                    break;
                case "3"://已确认完成
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity64) + data.getRefer() + "）");
                    tvNotify.setText("");
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity28));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(btControl, this::finish);
                    break;
                case "4"://申述中
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity71) + data.getCommand() + ",\n付款参考号：" + data.getRefer());
                    tvNotify.setText("");
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity28));
                    btControl.setVisibility(View.INVISIBLE);
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(btControl, () -> {
                    });
                    break;
                case "5"://订单取消
                    tvDesc.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity78));
                    tvNotify.setText("");
                    tvControl.setText("");
                    tvControlSecond.setText("");
                    btControl.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity82));
                    btControl.setVisibility(View.VISIBLE);
                    btControl.setEnabled(false);
                    btControl.setTextColor(getResources().getColor(R.color.white));
                    ClickUtil.click(tvControl, () -> {
                    });
                    ClickUtil.click(tvControlSecond, () -> {
                    });
                    ClickUtil.click(btControl, () -> {
                    });
                    break;
            }

        }

    }

    /**
     * 更新剩余时间
     *
     * @param aLong
     */
    private void updateTime(Long aLong) {
        String leftTime;
        if (aLong <= 0) {
            leftTime = App.INSTANCE.getString(R.string.strFabiSellDetailActivity120);
        } else {
            leftTime = TimeFormatUtil.SF_FORMAT_D.format(new Date(aLong * 1000));
        }
        if (isBuy) {
            tvSaleTo.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity44) + orderData.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity45) + NumberUtil.keepMax4(orderData.getTotalNum()) + "USDT");
            switch (orderData.getStatus()) {
                case "1"://未确认待付款
                    String desc = App.INSTANCE.getString(R.string.strFabiSellDetailActivity48) + leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity49) + orderData.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity50) + orderData.getRefer() + "）";
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(desc);
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.RED), desc.indexOf(leftTime), desc.indexOf(leftTime) + leftTime.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tvDesc.setText(spannableStringBuilder);
                    break;
                case "2"://已付款
                    tvNotify.setText(leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity59));
                    break;
                case "3"://已确认完成

                    break;
                case "4"://申述中

                    tvNotify.setText(leftTime + App.INSTANCE.getString(R.string.strFabiSellDetailActivity59));

                    break;

            }
        } else {
            tvSaleTo.setText(App.INSTANCE.getString(R.string.strFabiSellDetailActivity44) + orderData.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity84) + NumberUtil.keepMax4(orderData.getTotalNum()) + "USDT");
            switch (orderData.getStatus()) {
                case "1"://未确认待付款
                    String desc = App.INSTANCE.getString(R.string.strFabiSellDetailActivity87) + orderData.getUsername() + App.INSTANCE.getString(R.string.strFabiSellDetailActivity88) + leftTime + "内完成支付，\n付款参考号：" + orderData.getRefer();
                    tvDesc.setText(desc);
                    break;
                case "2"://已付款
                    break;
                case "3"://已确认完成
                    break;
                case "4"://申述中
                    break;

            }

        }
    }

    /**
     * 显示验证码底部弹窗
     */
    private void showCode() {
        if (codeDialog == null) {
            codeDialog = BottomUpUtil.getPay(this, mPresenter, (pwd) -> {
                codeDialog.dismiss();
                mPresenter.letGo(orderNum, isBuy ? "1" : "2", orderData.getId(), pwd);
            });
        }
        codeDialog.show();

    }

    /**
     * 支付完成提示弹窗
     */
    private void showPayTip() {
        if (payTipDialog == null) {
            payTipDialog = TipUtil.customTip1(this, App.INSTANCE.getString(R.string.strFabiSellDetailActivity146),
                    App.INSTANCE.getString(R.string.strFabiSellDetailActivity147),
                    App.INSTANCE.getString(R.string.strFabiSellDetailActivity28), () -> mPresenter.markPay(orderNum, orderData.getId(), isBuy ? "1" : "2"));
        }
        payTipDialog.show();
    }

    public void back() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeDispo != null && !timeDispo.isDisposed()) {
            timeDispo.dispose();
            timeDispo = null;
        }
        if (timerDispos != null && !timerDispos.isDisposed()) {
            timerDispos.dispose();
            timerDispos = null;
        }

    }
}
